<template>
	<view class="refund-container bottom-index">
		<!-- 加载中蒙版 -->
		<qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>

		<!-- 顶部导航栏 -->
		<qmy-custom-navbar title="申请退款"></qmy-custom-navbar>

		<!-- 退款表单 -->
		<view class="refund-form" :style="{paddingTop: menuObject.top + menuObject.height + 20 + 'px'}">
			<!-- 商品信息 -->
			<view class="goods-info" v-if="orderInfo">
				<view class="goods-item" v-for="(goods, index) in orderInfo.custom.goods_list" :key="index">
					<image class="goods-image" :src="goods.image" mode="aspectFill"></image>
					<view class="goods-detail">
						<text class="goods-name text-element-2">{{goods.name}}</text>
						<view class="goods-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{(goods.price/100).toFixed(2)}}</text>
							<text class="goods-quantity">x{{goods.quantity || 1}}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 退款金额 -->
			<view class="form-item">
				<view class="form-label">退款金额</view>
				<view class="refund-amount">
					<text class="price-symbol">¥</text>
					<text v-if="orderInfo" class="price-value">{{(orderInfo.total_fee/100).toFixed(2)}}</text>
					<text v-if="orderInfo" class="price-tip">（最多{{(orderInfo.total_fee/100).toFixed(2)}}元）</text>
				</view>
			</view>

			<!-- 退款原因 -->
			<view class="form-item">
				<view class="form-label required">退款原因</view>
				<view class="reason-select" @click="showReasonPicker">
					<text :class="{'placeholder': !selectedReason}">{{selectedReason || '请选择退款原因'}}</text>
					<text class="iconfont ic-you"></text>
				</view>
			</view>

			<!-- 退款说明 -->
			<view class="form-item">
				<view class="form-label">退款说明</view>
				<textarea class="refund-remark" v-model="remark" placeholder="请输入退款说明（选填）" maxlength="200"
					placeholder-class="textarea-placeholder"></textarea>
				<text class="word-count">{{remark.length}}/200</text>
			</view>

			<!-- 上传凭证 -->
			<view class="form-item">
				<view class="form-label">上传凭证</view>
				<view class="upload-box">
					<!-- 图片上传 -->
					<uni-file-picker ref="files" v-model="images" return-type="array" limit="6" mode="grid"
						file-mediatype="image" :sizeType="['compressed']"
						:image-styles="{width: '160rpx', height: '160rpx',border:false,background:'#f7f7f7',borderRadius:'20rpx',lineHeight:'160rpx'}">
					</uni-file-picker>
				</view>
			</view>
		</view>
		<!-- 底部定位发布按钮 -->
		<view @click="submitRefund" class="w-100 fixed-bottom bac-col-00b">
			<view class="w-100 bg-col-00b text-ali-c">
				<view class="fs-30 col-f fw-600">提交申请</view>
			</view>
		</view>

		<!-- 退款原因选择弹窗 -->
		<uni-popup ref="reasonPicker" type="bottom" background-color="#ffffff" borderRadius="30rpx 30rpx 0 0">
			<view class="slanted-rectangles br-30 pt-10 flex-dir-col ali-item-cen">
				<picker-view indicator-style="height: 50px;" :value="reasonArr" @change="onReasonChange"
					class="picker-view" style="height: 250rpx;">
					<picker-view-column>
						<view class="text-ali-c" style="line-height: 50px;" v-for="(item,index) in refundReasons"
							:key="index">
							{{item}}
						</view>
					</picker-view-column>
				</picker-view>
				<view class="w-100 flex-dir-row flex-x-spa ali-item-cen mt-20 text-ali-c fs-26">
					<view @click="cancelReason" class="border-bf col-87 br-20 gender-btn">取消</view>
					<view @click="confirmReason" class="bac-col-00b col-f br-20 gender-btn">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif
				dataLoaded: false,
				orderId: '', // 订单ID
				orderInfo: null, // 订单信息
				selectedReason: '', // 选中的退款原因
				tempReason: '', // 临时选中的退款原因
				remark: '', // 退款说明
				images: [], // 上传的图片列表
				refundReasons: [
					'商品质量问题',
					'商品与描述不符',
					'商品损坏',
					'多拍/拍错',
					'不想要了',
					'其他原因'
				],
				reasonArr: [0],
				reasonIndex: 0,
			}
		},
		computed: {
			// 是否可以提交
			canSubmit() {
				return this.selectedReason && this.orderInfo;
			}
		},
		onLoad(options) {
			if (options.id) {
				this.orderId = options.id;
				this.loadOrderDetail();
			}
		},
		methods: {
			// 加载订单详情
			async loadOrderDetail() {
				try {
					const res = await this.$Route('get-private-data', true).getOrderDetail(this.orderId);
					this.orderInfo = res.data[0];
					this.dataLoaded = true;
				} catch (err) {
					console.error('遇到错误:', err);
					let {
						code,
						msg
					} = this.$parseError(err);
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login');
						}
					}, 1000);
				}
			},

			// 显示退款原因选择器
			showReasonPicker() {
				this.$refs.reasonPicker.open();
			},

			// 取消选择
			cancelReason() {
				this.$refs.reasonPicker.close();
			},

			// 确认选择
			confirmReason() {
				this.selectedReason = this.refundReasons[this.reasonIndex];
				this.cancelReason();
			},

			// 更新选择的索引
			onReasonChange(e) {
				this.reasonIndex = e.detail.value[0];
			},

			// 提交退款申请
			async submitRefund() {
				// 防抖
				this.$debounce(async () => {
					if (!this.canSubmit) return this.$Toast('请选择退款原因');
					const params = {
						order_id: this.orderId,
						reason: this.selectedReason,
						remark: this.remark,
						images: this.images
					};
					this.$Route('add-private-data').applyRefund(params).then(res => {
						this.$Toast(res.msg);
						setTimeout(() => {
							this.getOpenerEventChannel().emit('refreshData', '')
							uni.navigateBack();
						}, 1500);
					}).catch(err => {
						console.error(err);
						let {
							code,
							msg
						} = this.$parseError(err);
						this.$Toast(msg);
						setTimeout(() => {
							if (code === 401) {
								this.$NavigateTo('/qmy_user/login');
							}
						}, 1000);
					});
				}, 1000, true, "submitRefund")
			}
		}
	}
</script>

<style lang="scss">
	.refund-container {
		min-height: 100vh;
		background-color: #f7f7f7;
	}

	.refund-form {
		padding: 20rpx;
	}

	.goods-info {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;

		.goods-item {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 2rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.goods-image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 12rpx;
				background-color: #f5f5f5;
				margin-right: 20rpx;
			}

			.goods-detail {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.goods-name {
					font-size: 28rpx;
					color: #333;
					line-height: 1.4;
				}

				.goods-price {
					display: flex;
					align-items: baseline;

					.price-symbol {
						font-size: 24rpx;
						color: #ff4f4f;
					}

					.price-value {
						font-size: 32rpx;
						color: #ff4f4f;
						font-weight: bold;
					}

					.goods-quantity {
						font-size: 26rpx;
						color: #999;
						margin-left: 12rpx;
					}
				}
			}
		}
	}

	.form-item {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;

		.form-label {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 16rpx;
			font-weight: 500;

			&.required::after {
				content: '*';
				color: #ff4f4f;
				margin-left: 4rpx;
			}
		}

		.refund-amount {
			display: flex;
			align-items: baseline;

			.price-symbol {
				font-size: 28rpx;
				color: #ff4f4f;
			}

			.price-value {
				font-size: 40rpx;
				color: #ff4f4f;
				font-weight: bold;
				margin: 0 8rpx;
			}

			.price-tip {
				font-size: 24rpx;
				color: #999;
			}
		}

		.reason-select {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			color: #333;

			.placeholder {
				color: #999;
			}

			.iconfont {
				font-size: 32rpx;
				color: #999;
			}
		}

		.refund-remark {
			width: 100%;
			height: 200rpx;
			font-size: 28rpx;
			line-height: 1.5;
			padding: 20rpx;
			background-color: #f7f7f7;
			border-radius: 12rpx;
			box-sizing: border-box;
		}

		.textarea-placeholder {
			color: #999;
		}

		.word-count {
			font-size: 24rpx;
			color: #999;
			text-align: right;
			margin-top: 8rpx;
		}

	}


	.slanted-rectangles {
		position: relative;
		width: 100%;
		background-color: white;
		border-top-left-radius: 40rpx;
		border-top-right-radius: 40rpx;
		padding-bottom: 20rpx;
		bottom: -20rpx;
		z-index: 2;

		&::before {
			content: '';
			position: absolute;
			top: -46rpx;
			z-index: -1;
			left: 0;
			width: 100%;
			height: 50%;
			background-color: white;
			transform: skewY(3deg);
			border-radius: 40rpx 40rpx 0 0;
		}
	}

	.picker-view {
		width: 750rpx;
		height: 350rpx;
		margin-top: 20rpx;
	}

	.gender-btn {
		width: 270rpx;
		height: 80rpx;
		line-height: 80rpx;
	}

	.text-element-2 {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		padding-top: 30rpx;
		padding-bottom: 30rpx !important;
		padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)) !important;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom)) !important;
		z-index: 99;
		transition: background-color 0.2s ease;
	}

	.fixed-bottom:active {
		background-color: #11b051 !important;
		/* 点击时背景颜色变化 */
	}
</style>